package cn.east196.xproto.core;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;

public class HexKit {

	public static String toHex(List<Meta> metas,JSONObject jsonObject) throws Exception {
		int size= metas.stream().map(meta->meta.getSize()).reduce(0, (a,b)->a+b);
		ByteBuffer byteBuffer = ByteBuffer.allocate(size);
		for (Meta meta : metas) {
				String value = jsonObject.getString(meta.getName());
				int len = meta.getSize()*2;
				String hexPart = HexUtil.encodeHexStr(value);
				String filledHexPart= StrUtil.fillBefore(hexPart, '0', len);
				byteBuffer.put(HexUtil.decodeHex(filledHexPart));
		}
		return HexUtil.encodeHexStr(byteBuffer.array()).toUpperCase();
	}
	
	public static JSONObject toJsonObject(List<Meta> metas,String hex) throws Exception {
		int size= metas.stream().map(meta->meta.getSize()).reduce(0, (a,b)->a+b);
		ByteBuffer byteBuffer = ByteBuffer.allocate(size);
		byteBuffer.put(HexUtil.decodeHex(hex));
		byteBuffer.rewind();
		JSONObject jsonObject=new JSONObject();
		for (Meta meta : metas) {
			    byte[] bytes = new byte[size];
				byteBuffer.get(bytes);
				String hexPart = HexUtil.encodeHexStr(bytes);
				jsonObject.put(meta.getName(), HexUtil.decodeHexStr(hexPart));
		}
		return jsonObject;
	}
	
	public static void main(String[] args) throws Exception {
		// String hex = "7e02000076178000000005000300020000000000020158834706ca2e59000000020000180118005524fe58e6020001640700504e312e3032304d323647303154312c3836343030532830292c323032533b54494d453a30303a30303b49434349443a38393836303242363131313637303239323033373b323836362c313241463b3230cc7e";
		Meta meta =new Meta();
		meta.setName("name");
		meta.setOrder(1);
		meta.setSize(3);
		meta.setType("int32");
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("name", "eat");
		List<Meta> metas=new ArrayList<>();
		metas.add(meta);
		String hex = toHex(metas,jsonObject);
		System.out.println(hex);
		JSONObject jsonObject2 = toJsonObject(metas,hex);
		System.out.println(jsonObject2);
		
//		ByteBuffer byteBuffer = ByteBuffer.allocate(hex.length()/2);
//		byteBuffer.put(HexUtil.decodeHex(hex));
//		System.out.println(HexUtil.encodeHexStr(byteBuffer.array()).toUpperCase());
		
		
	}
	
}
